<?php
/**
 * 定时任务
 * @author Administrator
 *
 */
class Crontab extends Controller{
    var $user = null;
    function Crontab(){
        parent::Controller();
        $this->user = array(
            'userId'    => 0,//用户ID
            'userName'  => '',//用户名称
            'userRole'  => 0,//用户角色
            'userLimit' => array(),//用户权限
        );
        //设置超时
        set_time_limit(20);
    }
    /**
     * 预算自动审核
     */
    function budgetAutoAudit(){
        //单店项目预算自动审核
        $this->budgetSingleProjectAutoAudit();
        //单店车展自动审核
        $this->budgetSingleCarshowAutoAudit();
        //增强类RMP专项自动审核
        $this->budgetSingleRmpAutoAudit();
    }
    /**
     * 单店项目预算自动审核
     */
    function budgetSingleProjectAutoAudit(){
        $this->load->model('sProjectModel');
        $this->load->model('sPGxModel');
        $this->load->model('sPOfflineModel');
        //项目ID集
        $projectIds = array();
        $time = strtotime('-1 day');
        echo "<font color='red'>开始项目预算自动审核</font><br>";
        //广宣ID集
        $gxList = $this->sPGxModel->getList(array('budgetAuditRs'=>0,'budgetSubTime < '=>$time), NULL, NULL, 'id,projectId,budgetSubTime');
        foreach ($gxList as $v){
            $projectIds[(int)$v['projectId']]['gx'][] = (int)$v['id'];
        }
        //线下ID集
        $offlineList = $this->sPOfflineModel->getList(array('budgetAuditRs'=>0,'budgetSubTime < '=>$time), NULL, NULL, 'id,projectId,budgetSubTime');
        foreach ($offlineList as $v){
            $projectIds[(int)$v['projectId']]['offline'][] = (int)$v['id'];
        }
        if ($projectIds){
            $projectList = $this->sProjectModel->getList(array('id'=>array('in', array_keys($projectIds) )));
            foreach ($projectList as $v){
                if ($v['fixedMoney'] >= $v['budgetApply']){//不超过定额,一天内自动审核
                    if ($time - $v['budgetSubTime'] > 86400){
                        if (isset($projectIds[$v['id']]['gx'])){
                            foreach ($projectIds[$v['id']]['gx'] as $gxv){
                                $this->sPGxModel->budgetAudit($gxv, 1, $this->user);
                            }
                        }
                        if (isset($projectIds[$v['id']]['offline'])){
                            foreach ($projectIds[$v['id']]['offline'] as $offlinev){
                                $this->sPOfflineModel->budgetAudit($offlinev, 1, $this->user);
                            }
                        }
                        $this->sProjectModel->budgetUpdateStatus($v['id']);
                        $this->sProjectModel->updateMoney($v['id']);
                        echo "项目方案编号为【".$v['id']."】预算自动审核成功<br> \n";
                        usleep(500);
                    }
                }else{//超过定额，七天内审核
                    if ($time - $v['budgetSubTime'] > 86400*7){
                        if (isset($projectIds[$v['id']]['gx'])){
                            foreach ($projectIds[$v['id']]['gx'] as $gxv){
                                $this->sPGxModel->budgetAudit($gxv, 1, $this->user);
                            }
                        }
                        if (isset($projectIds[$v['id']]['offline'])){
                            foreach ($projectIds[$v['id']]['offline'] as $offlinev){
                                $this->sPOfflineModel->budgetAudit($offlinev, 1, $this->user);
                            }
                        }
                        $this->sProjectModel->budgetUpdateStatus($v['id']);
                        $this->sProjectModel->updateMoney($v['id']);
                        echo "项目方案编号为【".$v['id']."】预算自动审核成功<br> \n";
                        usleep(500);
                    }
                }
                //暂停500微妙
                echo str_repeat(" ",4096);                
            }
        }
        echo "<font color='red'>结束项目预算自动审核</font><br>";
    }
    /**
     * 车展预算自动审核
     */
    function budgetSingleCarshowAutoAudit(){
        $this->load->model('sCarshowModel');
        $this->load->model('sCGxModel');
        $this->load->model('sCRentModel');
        $this->load->model('sCMatchingModel');
        //项目ID集
        $projectIds = array();
        $time = strtotime('-7 day');
        echo "<font color='red'>开始非城市地方车展预算自动审核</font><br>";
        //广宣ID集
        $gxList = $this->sCGxModel->getList(array('budgetAuditRs'=>0,'budgetSubTime < '=>$time));
        foreach ($gxList as $v){
            $projectIds[(int)$v['carshowId']]['gx'][] = (int)$v['id'];
        }
        //场租ID集
        $rentList = $this->sCRentModel->getList(array('budgetAuditRs'=>0,'budgetSubTime < '=>$time));
        foreach ($rentList as $v){
            $projectIds[(int)$v['carshowId']]['rent'][] = (int)$v['id'];
        }
        //车展配套ID集
        $matchingList = $this->sCMatchingModel->getList(array('budgetAuditRs'=>0,'budgetSubTime < '=>$time));
        foreach ($matchingList as $v){
            $projectIds[(int)$v['carshowId']]['matching'][] = (int)$v['id'];
        }
        if ($projectIds){
            $carshowList = $this->sCarshowModel->getList(array('id'=>array('in', array_keys($projectIds))) );
            foreach ($carshowList as $v){
                if (isset($projectIds[$v['id']]['gx'])){
                    foreach ($projectIds[$v['id']]['gx'] as $gxv){
                        $this->sCGxModel->budgetAudit($gxv, 1, $this->user);
                    }
                }
                if (isset($projectIds[$v['id']]['rent'])){
                    foreach ($projectIds[$v['id']]['rent'] as $rentv){
                        $this->sCRentModel->budgetAudit($rentv, 1, $this->user);
                    }
                }
                if (isset($projectIds[$v['id']]['matching'])){
                    foreach ($projectIds[$v['id']]['matching'] as $matchingv){
                        $this->sCMatchingModel->budgetAudit($matchingv, 1, $this->user);
                    }
                }
                $this->sCarshowModel->budgetUpdateStatus($v['id']);
                $this->sCarshowModel->updateMoney($v['id']);
                
                echo "地方车展编号为【".$v['id']."】预算自动审核成功<br> \n";
                //暂停500微妙
                echo str_repeat(" ",4096);
                usleep(500);
            }
        }
        echo "<font color='red'>结束非城市地方车展预算自动审核</font><br>";
    }
    /**
     * 增强类RMP专项预算自动审核
     */
    function budgetSingleRmpAutoAudit(){
        $this->load->model('sRmpModel');
        $this->load->model('sRGxModel');
        $this->load->model('sROfflineModel');
        //项目ID集
        $projectIds = array();
        $time = strtotime('-7 day');
        echo "<font color='red'>开始增强类RMP专项预算自动审核</font><br>";
        //广宣ID集
        $gxList = $this->sRGxModel->getList(array('budgetAuditRs'=>0,'budgetSubTime < '=>$time));
        foreach ($gxList as $v){
            $projectIds[(int)$v['projectId']]['gx'][] = (int)$v['id'];
        }
        //线下ID集
        $offlineList = $this->sROfflineModel->getList(array('budgetAuditRs'=>0,'budgetSubTime < '=>$time));
        foreach ($offlineList as $v){
            $projectIds[(int)$v['projectId']]['offline'][] = (int)$v['id'];
        }
        if ($projectIds){
            $projectList = $this->sRmpModel->getList(array('id'=>array('in', array_keys($projectIds) )));
            foreach ($projectList as $v){
                if (isset($projectIds[$v['id']]['gx'])){
                    foreach ($projectIds[$v['id']]['gx'] as $gxv){
                        $this->sRGxModel->budgetAudit($gxv, 1, $this->user);
                    }
                }
                if (isset($projectIds[$v['id']]['offline'])){
                    foreach ($projectIds[$v['id']]['offline'] as $offlinev){
                        $this->sROfflineModel->budgetAudit($offlinev, 1, $this->user);
                    }
                }
                $this->sRmpModel->budgetUpdateStatus($v['id']);
                $this->sRmpModel->updateMoney($v['id']);
                echo "增强类RMP专项方案编号为【".$v['id']."】预算自动审核成功<br> \n";
                usleep(500);
                //暂停500微妙
                echo str_repeat(" ",4096);
            }
        }
        echo "<font color='red'>结束增强类RMP专项预算自动审核</font><br>";
    }
    /**
     * 巡展同步
     */
    function xunSync(){
        //error_reporting(E_ALL);
        //ini_set('display_errors', 1);
        //设置超时时间
        set_time_limit(0);
        $year = 2015;//当前年份
        $nowMonth = (int)date("m");//当前月份
        $updateMax = 10;//每次同步数量
        $state = isset($_GET['state']) ? (int)$_GET['state'] : 0;//获取标识（0：待同步，1：已同步）
        //加载巡展同步类
        $this->load->library('XunSync', NULL, 'XunSync');
        $nowMonth = 12;
        for ($month = 7; $month <= $nowMonth; $month++){
            echo '【更新'.$month.'月份数据开始】<br>';
            //项目预算同步
            $beginNumber = 1;
            do{
                $rs = $this->XunSync->budgetProjectSync($year, $month, $updateMax, $beginNumber, '08', $state);
                $codeStr = $rs['code']==1?'<font color="green">成功</font>':'<font color="red">失败</font>';
                $log = '更新项目预算情况（[年份：'.$year.'],[月份:'.$month.'],[更新状态：'.$codeStr.'],[更新反馈：'.$rs['msg'].'],[更新数量：'.(isset($rs['data']['updateCount']) ? $rs['data']['updateCount'] : 0).']）<br>';
                echo $log;
                //记录错误日志
                if ($rs['code'] == 0){
                    $this->xunSyncRecord('项目预算同步错误', $log);
                }
                echo str_repeat(" ",4096);
                //usleep(500);
                $updateCount = isset($rs['data']['total']) ? $rs['data']['total'] : 0;
                $state == 1 && $beginNumber ++;
            }while ( $updateCount == $updateMax);
            //广宣预算同步
            $beginNumber = 1;
            do{
                $rs = $this->XunSync->budgetGxSync($year, $month, $updateMax, $beginNumber, '08', $state);
                $codeStr = $rs['code']==1?'<font color="green">成功</font>':'<font color="red">失败</font>';
                $log = '更新广宣预算情况（[年份：'.$year.'],[月份:'.$month.'],[更新状态：'.$codeStr.'],[更新反馈：'.$rs['msg'].'],[更新数量：'.(isset($rs['data']['updateCount']) ? $rs['data']['updateCount'] : 0).']）<br>';
                echo $log;
                //记录错误日志
                if ($rs['code'] == 0){
                    $this->xunSyncRecord('广宣预算同步错误', $log);
                }
                echo str_repeat(" ",4096);
                //usleep(500);
                $updateCount = isset($rs['data']['total']) ? $rs['data']['total'] : 0;
                $state == 1 && $beginNumber ++;
            }while ( $updateCount == $updateMax);
            //线下活动预算同步
            $beginNumber = 1;
            do{
                $rs = $this->XunSync->budgetOfflineSync($year, $month, $updateMax, $beginNumber, '08', $state);
                $codeStr = $rs['code']==1?'<font color="green">成功</font>':'<font color="red">失败</font>';
                $log ='更新线下活动预算情况（[年份：'.$year.'],[月份:'.$month.'],[更新状态：'.$codeStr.'],[更新反馈：'.$rs['msg'].'],[更新数量：'.(isset($rs['data']['updateCount']) ? $rs['data']['updateCount'] : 0).']）<br>';
                echo $log;
                //记录错误日志
                if ($rs['code'] == 0){
                    $this->xunSyncRecord('线下活动预算同步错误', $log);
                }
                echo str_repeat(" ",4096);
                //usleep(500);
                $updateCount = isset($rs['data']['total']) ? $rs['data']['total'] : 0;
                $state == 1 && $beginNumber ++;
            }while ( $updateCount == $updateMax);
            //项目结算同步
            $beginNumber = 1;
            do{
                $rs = $this->XunSync->settleProjectSync($year, $month, $updateMax, $beginNumber, '08', $state);
                $codeStr = $rs['code']==1?'<font color="green">成功</font>':'<font color="red">失败</font>';
                $log ='更新项目结算情况（[年份：'.$year.'],[月份:'.$month.'],[更新状态：'.$codeStr.'],[更新反馈：'.$rs['msg'].'],[更新数量：'.(isset($rs['data']['updateCount']) ? $rs['data']['updateCount'] : 0).']）<br>';
                echo $log;
                //记录错误日志
                if ($rs['code'] == 0){
                    $this->xunSyncRecord('项目结算同步错误', $log);
                }
                echo str_repeat(" ",4096);
                //usleep(500);
                $updateCount = isset($rs['data']['total']) ? $rs['data']['total'] : 0;
                $state == 1 && $beginNumber ++;
            }while ( $updateCount == $updateMax);
            //广宣结算同步
            $beginNumber = 1;
            do{
                $rs = $this->XunSync->settleGxSync($year, $month, $updateMax, $beginNumber, '08', $state);
                $codeStr = $rs['code']==1?'<font color="green">成功</font>':'<font color="red">失败</font>';
                $log ='更新广宣结算情况（[年份：'.$year.'],[月份:'.$month.'],[更新状态：'.$codeStr.'],[更新反馈：'.$rs['msg'].'],[更新数量：'.(isset($rs['data']['updateCount']) ? $rs['data']['updateCount'] : 0).']）<br>';
                echo $log;
                //记录错误日志
                if ($rs['code'] == 0){
                    $this->xunSyncRecord('广宣结算同步错误', $log);
                }
                echo str_repeat(" ",4096);
                //usleep(500);
                $updateCount = isset($rs['data']['total']) ? $rs['data']['total'] : 0;
                $state == 1 && $beginNumber ++;
            }while ( $updateCount == $updateMax);
            //线下活动结算同步
            $beginNumber = 1;
            do{
                $rs = $this->XunSync->settleOfflineSync($year, $month, $updateMax, $beginNumber, '08', $state);
                $codeStr = $rs['code']==1?'<font color="green">成功</font>':'<font color="red">失败</font>';
                $log ='更新线下活动结算情况（[年份：'.$year.'],[月份:'.$month.'],[更新状态：'.$codeStr.'],[更新反馈：'.$rs['msg'].'],[更新数量：'.(isset($rs['data']['updateCount']) ? $rs['data']['updateCount'] : 0).']）<br>';
                echo $log;
                //记录错误日志
                if ($rs['code'] == 0){
                    $this->xunSyncRecord('线下活动结算同步错误', $log);
                }
                echo str_repeat(" ",4096);
                usleep(500);
                $updateCount = isset($rs['data']['total']) ? $rs['data']['total'] : 0;
                $state == 1 && $beginNumber ++;
            }while ( $updateCount == $updateMax);
            echo '【更新'.$month.'月份数据结束】<br>';
        }
    }
    /**
     * 记录巡展同步日志
     * @param string $typeName
     * @param string $log
     */
    function xunSyncRecord($typeName, $log){
        $this->load->model('xLogModel');
        $this->xLogModel->add(array('typeName'=>$typeName,'log'=>$log,'createTime'=>date("Y-m-d H:i:s")));
        //邮件提醒
        $this->load->library('email');
        //发件人
        $this->email->from('zhaojianhui129@163.com', '巡展同步邮件警报');
        //收件人
        $this->email->to('zhaojianhui129@vip.qq.com');
        //抄送
        $this->email->cc(array('ivy.huang@bluedoorindex.com'));
        //暗送
        //$this->email->bcc('them@their-example.com');
        
        $this->email->subject($typeName);
        $this->email->message($log);
        
        $this->email->send();
        //echo $this->email->print_debugger();
    }
    /**
     * 删除无效的巡展
     * @return [type] [description]
     */
    function xunDel(){
        //设置超时时间
        set_time_limit(0);
        $this->load->model('xProjectModel');
        $this->load->model('xPGxModel');
        $this->load->model('xPOfflineModel');
        $this->load->model('xPODetailModel');
        $delList = $this->xProjectModel->getList(array('siteSpecs !='=>1));
        foreach ($delList as $k => $v) {
            $gxList = $this->xPGxModel->getList(array('activityId'=>$v['activityId']));
            foreach ($gxList as $gxK => $gxV) {
                $this->xPGxModel->del(array('costNo'=>$gxV['costNo']), '*');
            }
            $offlineList = $this->xPOfflineModel->getList(array('activityId'=>$v['activityId']));
            foreach ($offlineList as $offK => $offV) {
                $this->xPODetailModel->del(array('offlineCostNo'=>$offV['costNo']), '*');
                $this->xPOfflineModel->del(array('costNo'=>$offV['costNo']), '*');
            }
            $this->xProjectModel->del(array('activityId'=>$v['activityId']), '*');
            echo "删除项目".$v['activityId']."成功<br>";
            echo str_repeat(" ",4096);
            usleep(500);
        }
    }
}